
/**
 * @file main
 *
 */
#include <string.h>
#include "home_ui.h"
#include <fcntl.h>
#include <pthread.h>
#include <sys/stat.h>

char *str_path = "";

static pthread_t fevdev_tid;
static pthread_mutex_t fevdev_lock;
lv_obj_t * cont;

void testf(void) {
    char *fullPath1="hellolk";
    printf("fullPath1 address:%d sizeof: %d path:%s char:%c\n", fullPath1, sizeof(*fullPath1),fullPath1,*(fullPath1+6));

    char fullPath2[]="hellolk";
    //fullPath1=malloc(2 * sizeof(char)); 
    //realloc
    printf("fullPath2 address:%d sizeof: %d path:%s char:%c\n", fullPath2, sizeof(fullPath2), fullPath2, *(fullPath2+6));

    int* p = (int*)malloc(10*sizeof(int));    //开辟10个整型大小空间
    if (p == NULL)       //如果开辟失败,则打印错误原因
    {
        //打印错误原因的一个方式
        //printf("%s\n", strerror(errno));
    }
    else
    {
        int i = 0;
        for (i = 0; i < 10; i++)    //遍历并初始化打印这10个整型空间
        {
            *(p + i) = i;
            printf("%d ", *(p + i));
        }
        //可以正常使用p指针来操作这片空间了
    }
    printf("\n");
    int* p2 = (int*)realloc(p, 15 * sizeof(int));//将这块空间扩容到15个整型
    if (p2 == NULL)
    {
        //printf("%s\n", strerror(errno));
    }
    else
    {
        int i = 0;
        for (i = 0; i < 15; i++)    //遍历并打印这15个整型空间
        {
            *(p2 + i)=i;
            printf("%d ", *(p2 + i));
        }
    }

    //free(p);    //释放p的内存空间
    //p = NULL;         //将指针p置为NULL,防止其变成野指针
}


char* getfilename(char *dest2,char *src) {
    strcpy(dest2, str_path);
    strcat(dest2, "/");
    strcat(dest2, src); 
    printf("New string: %s\n", dest2);
    return *dest2; 
}
// 动态增加数组大小并追加字符串的示例函数（需要额外的逻辑来处理内存分配）
void append_if_not_found_dynamic(char ***arr, int *size, const char *to_append, const char *to_find) {
    int found = 0;
    for (int i = 0; i < *size; i++) {
        if (strstr((*arr)[i], to_find) != NULL) {
            found = 1;
            break;
        }
    }
    if (!found) {
        // 如果没有找到，动态增加数组大小并追加字符串（这里仅为示例，实际实现会更复杂）
        *arr = (char **)realloc(*arr, (*size + 1) * sizeof(char *)); // 重新分配内存以增加一个元素
        if (*arr != NULL) { // 检查realloc是否成功
            (*arr)[*size] = malloc(strlen(to_append) + 1); // 为新元素分配内存
            strcpy((*arr)[*size], to_append); // 复制字符串到新位置
            (*size)++; // 更新数组大小
        } else {
            // 处理内存分配失败的情况...
        }
    }
}
// 假设我们有以下函数来追加字符串（如果需要的话）
void append(char **arr[], const char *str) {
    int found = 0;
    int size=2;
    for (int i = 0; i < size; i++) {
        //printf("found %s",arr[i]);        
        if (strstr(arr[i], str) != NULL) {
            found = 1;
            break;
        }
    }
    if (!found) {
        printf("address1: %d",**arr);
        //realloc(**arr, 1* sizeof(char *)); 
        //realloc(**arr, (size + 1) * sizeof(char *)); // 重新分配内存以增加一个元素
        /*
        *arr = (char **)realloc(*arr, (size + 1) * sizeof(char *)); // 重新分配内存以增加一个元素
        if (*arr != NULL) { // 检查realloc是否成功
            //(*arr)[size] = malloc(strlen(str) + 1); // 为新元素分配内存
            //strcpy((*arr)[size], str); // 复制字符串到新位置

        } else {
        }*/
        /**
         * 追加情况
         */
        lv_obj_t * label;
        lv_obj_t * obj;
        obj = lv_btn_create(cont);
        lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, 2, 1,LV_GRID_ALIGN_STRETCH, 1, 1);

        label = lv_label_create(obj);
        lv_label_set_text_fmt(label, "0255");
        lv_obj_center(label);

    }
}

static void *file_thread(void *arg){
    /*
    pthread_mutex_lock(&evdev_lock);
    evdev_val[0] = evdev_val[1];
    evdev_val[1].x = x;
    evdev_val[1].y = y;
    evdev_val[1].button = button;
    pthread_mutex_unlock(&evdev_lock);
    */
    // 示例：创建一个字符串数组并初始化
    char *arr[5] = {"Hello", "World"}; // 确保至少有一个空字符串用于追加
    const char *to_append = "Example";
    const char *to_find = "World";
    append(arr, to_append);
    printf("in thread!\n");
}

void btn_exit_event_cb1(lv_obj_t * btn_exit, lv_event_t event){
    /* Exit the program and release resources */
    printf("set00000 led status failed!\n");
}


void rk_demo_init(void){
    lv_obj_t* btn01 = lv_btn_create(lv_scr_act());
    lv_obj_t * label01 = lv_label_create(btn01);
    lv_label_set_text(label01, "test");
    lv_obj_set_pos(btn01, 10+100, 10);
    lv_obj_set_size(btn01, 100, 50);
    lv_obj_add_event_cb(btn01, btn_exit_event_cb1, LV_EVENT_CLICKED, NULL);
}

void rk_desk_init(void){
    static lv_coord_t col_dsc[] = {70, 70, 70, LV_GRID_TEMPLATE_LAST};
    static lv_coord_t row_dsc[] = {50, 50, 50, LV_GRID_TEMPLATE_LAST};
    cont = lv_obj_create(lv_scr_act());
    lv_obj_set_grid_dsc_array(cont,col_dsc, row_dsc);
    lv_obj_set_size(cont, 480, 320);
    lv_obj_set_layout(cont, LV_LAYOUT_GRID);

    uint32_t i;
    DIR *dir;
    str_path ="/data";
    //const char* p = const_cast<char*>(str_path.c_str());
    dir = opendir(str_path);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }
    i=0;
    struct dirent *entry;
    struct stat fileStat;
    while ((entry = readdir(dir)) != NULL) {
        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))continue;
        uint8_t col = i % 3; uint8_t row = i / 3;
        char fullPath[1024];
        snprintf(fullPath, sizeof(fullPath), "%s/%s", str_path, entry->d_name);
        printf("fullPath address:%d,sizeof: %d path:%s\n" ,fullPath,sizeof(fullPath),fullPath);


        if (stat(fullPath, &fileStat) < 0) {
            perror("Failed to get file status");
            continue;
        }
        if (S_ISDIR(fileStat.st_mode)) {
            if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
                printf("Directory: %s\n", fullPath);
            }
        } else if (S_ISREG(fileStat.st_mode)) {
            //printf("File: %s\n", fullPath);
            lv_obj_t * label;
            lv_obj_t * obj;
            obj = lv_btn_create(cont);
            lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, col, 1,LV_GRID_ALIGN_STRETCH, row, 1);

            label = lv_label_create(obj);
            lv_label_set_text_fmt(label, (char *)entry->d_name);
            lv_obj_center(label);
            //const char * user_message = (char *)entry->d_name;
            //const char user_message[] = "Hello, LVGL!";//这样子不行
            const char *user_message =*fullPath;//这样子行 问题出在那
            //const char *user_message = "a.py";//这样子行 问题出在那
            lv_obj_add_event_cb(obj, btn_exit_event_cb, LV_EVENT_CLICKED, (void *)user_message);
            i++;
        } else {
            printf("Other: %s\n", fullPath);
        }
    }
    closedir(dir);
    //pthread_create(&fevdev_tid, NULL, file_thread, NULL);
}

void btn_exit_event_cb(lv_event_t * e){
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * btn = lv_event_get_target(e);
    char *user_data =lv_event_get_user_data(e);

    //obj->spec_attr->event_dsc[obj->spec_attr->event_dsc_cnt];
    //void * user_data = lv_event_get_user_data(e);
    if(user_data  != NULL) {
        printf("User data0: %d\n", user_data );
        //printf("User data0: %d\n", *user_data );
        printf("User data0: %d\n", *(&user_data));
        printf("User data0: %d\n", &user_data);
        printf("User data0: %d\n", &user_data+0x1);
        printf("User data0: %d\n", *(&user_data+1));
        //printf("User data1: %s\n", user_data);
        //char *dest = malloc(strlen((str_path)+ strlen(user_data)+1) * sizeof(char)); 
        //getfilename(dest,user_data); 
        //exec_comand(dest);
        //free(dest); // 释放内存
    }
   
}

void exec_comand(char *file){
    FILE *fp;
    char path[1035];
    char *exec="python3 ";
    char *comand = malloc(strlen((exec)+ strlen(file)+1) * sizeof(char)); 
    strcpy(comand, exec);
    strcat(comand, file); 
    fp = popen(comand, "r");
    if (fp == NULL) {
        perror("popen failed");
        return ;
    }
    while (fgets(path, sizeof(path), fp) != NULL) {
        printf("%s", path); // 打印输出结果
    }
    pclose(fp); // 关闭管道并等待子进程结束
}